'use strict'

var config = require('../config')
var http = require('../lib/http')

var userModel = require('../models/user')

exports.wechatLogin = function*(next){
  var wechatCfg = config.wechat

  var callbackUrl = encodeURIComponent(`${wechatCfg.tunnelUrl}/callback`) // 回调地址公网可访问
  var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechatCfg.appid}&redirect_uri=${callbackUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  this.redirect(url)
}

exports.wechatCallback = function*(next){
  var code = this.query.code
  var wechatCfg = config.wechat
  var url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wechatCfg.appid}&secret=${wechatCfg.appsecert}&code=${code}&grant_type=authorization_code`
  var json = yield http.getJSON(url)
  console.dir(json)
  var openid = json.openid
  var token = json.access_token
  var infoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openid}&lang=zh_CN`
  var userinfo = yield http.getJSON(infoUrl)
  // console.log('userinfo', userinfo)

  // 方式1：使用微信用户信息直接登陆，无需登陆和绑定
  // yield this.render('success',{'userinfo':userinfo})
  
  // 方式2：将微信和平台账号绑定
  var user = yield userModel.getUserByOpenid(openid)

  // 查询DB是否进行了绑定
  if(user) yield this.render('success',{'userinfo':user,'title':'登陆成功'})
  else yield this.render('login',{'openid':openid,'title':'请登陆'})
}

exports.bindAccount = function*(next){
  var data = this.request.body
  var account = data.account,
    password = data.password,
    openid = data.openid

  var ret = yield userModel.bindAccount(account,password,openid)

  if (ret === 1) yield this.body = {success:true,msg:'bind succuess,please rescan the qrcode to login'}
  else yield this.body = {success:false,msg:'bind failure'}
}
